<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\BaseController;
use app\common\lib\file\Files;
use app\common\lib\Str;
use think\facade\View;

#[path('/index/controller', 'file path')]
#[class('Base', 'Base data handel')]
class Base extends BaseController
{
    public $user_data = null;
    public function initialize()
    {
        parent::initialize();

        $m = str_replace('/', '', Request()->root());
        $c = strtolower(Request()->controller());
        $a = strtolower(Request()->action());

        $config = config('common');

        $this->user_data = session(config('user.session'));

        // 获取 host name
        $http_protocol = ((int) $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://';
        $host_name     = $http_protocol . $_SERVER['SERVER_NAME'];

        // 实例化文件处理类
        $this->file = new Files();

        // 处理文件路径
        $this->filePath();

        View::assign([
            'm'          => $m,
            'c'          => $c,
            'a'          => $a,
            'config'     => $config,
            'user_data'  => $this->user_data,

            'host_name'  => $host_name,

            'go_back'    => $this->go_back,
            'navigation' => $this->navigation,

            'path'       => $this->path,
            'full_path'  => $this->full_path,
        ]);
    }

    public function filePath()
    {
        // 获取系统文件路径
        $this->def_path = config('file.default_path');

        // 获取 url 地址, 并去除多余斜杠
        $this->path = input('param.path', '', 'trim');
        $this->path = Str::challenge('//', '/', $this->path);

        // 获取返回上一级路径
        $this->go_back = $this->goBack($this->path);

        // 获取文件导航
        $this->navigation = $this->navigation($this->path);

        // 将系统文件路径和 url 路径 进行拼接
        $this->full_path = $this->def_path . $this->path;
    }

    public function goBack($path = '')
    {
        $pos     = strrpos($path, '/');
        $go_back = '/';

        if ($pos) {
            $go_back = '/index/?path=' . substr($path, 0, $pos);
        }

        return $go_back;
    }

    // 获取文件导航
    public function navigation($path = '')
    {
        // 以 '/' 进行分割目录
        $navigation = explode("/", $path);

        $remenu  = '';
        $new_nav = [];
        foreach ($navigation as $key => $value) {

            if (!$value) {
                continue;
            }
            $remenu    = $remenu . '/' . $value;
            $new_nav[] = [
                'path'      => $remenu,
                'file_name' => $value,
            ];
        }

        return $new_nav;
    }
}
